<template>
	<view class="chat-container">
		<!-- 自定义导航栏 -->
		<view class="chat-header" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="header-content">
				<view class="header-left" @click="goBack">
					<text class="back-icon">←</text>
				</view>
				<view class="header-center" @click="viewProfile">
					<view class="avatar-container">
						<image class="header-avatar" :src="chatInfo.avatar" mode="aspectFill" @error="onAvatarError" />
						<!-- 客服标识 -->
						<view v-if="chatInfo.isCustomerService" class="service-badge">
							<text class="service-text">客服</text>
						</view>
					</view>
					<view class="header-info">
						<text class="header-name">{{ chatInfo.nickname }}</text>
						<text class="header-status" :class="{ 'service-status': chatInfo.isCustomerService }">
							{{ chatInfo.isCustomerService ? '人工客服' : (chatInfo.isOnline ? '在线' : '离线') }}
						</text>
					</view>
				</view>
				<view class="header-right" @click="showChatMenu">
					<text class="menu-icon">⋯</text>
				</view>
			</view>
		</view>
		
		<!-- 消息列表 -->
		<scroll-view
			class="message-list"
			scroll-y="true"
			:scroll-into-view="scrollIntoView"
			@scrolltoupper="loadMoreMessages"
		>
			<!-- 空状态提示 -->
			<view v-if="!isLoading && messages.length === 0" class="empty-messages">
				<text class="empty-text">暂无聊天记录</text>
				<text class="empty-desc">开始你们的第一次对话吧</text>
			</view>

			<view
				v-for="(message, index) in messages"
				:key="message.id"
				:id="'message-' + message.id"
				class="message-item"
				:class="{ 'message-self': message.isSelf }"
			>
				<!-- 时间分割线 -->
				<view v-if="showTimeLabel(message, index)" class="time-divider">
					<text class="time-text">{{ formatMessageTime(message.timestamp) }}</text>
				</view>
				
				<!-- 消息内容 -->
				<view class="message-content">
					<!-- 对方的消息，头像在左侧 -->
					<template v-if="!message.isSelf">
						<image
							class="message-avatar"
							:src="message.sender.avatar"
							mode="aspectFill"
							@error="onAvatarError"
						/>
						<view class="message-bubble bubble-other" :class="{ 'video-message': message.type === 'video' }">
							<!-- 文本消息 -->
							<text v-if="message.type === 'text'" class="text-content">{{ message.content }}</text>

							<!-- 图片消息 -->
							<image
								v-else-if="message.type === 'image'"
								class="image-content"
								:src="message.imageUrl || message.content"
								mode="aspectFit"
								@click="previewImage(message.imageUrl || message.content)"
							/>

							<!-- 视频消息 -->
							<view v-else-if="message.type === 'video'" class="video-content" @click="playVideo(message)">
								<video
									class="video-player"
									:src="message.videoUrl || message.content"
									:poster="message.videoCoverUrl"
									controls
									:show-center-play-btn="true"
									:show-play-btn="true"
								/>
							</view>

							<!-- 语音消息 -->
							<view v-else-if="message.type === 'voice'" class="voice-content" @click="playVoice(message)">
								<text class="voice-icon">🎤</text>
								<text class="voice-duration">{{ message.duration }}''</text>
							</view>
						</view>
					</template>
					
					<!-- 自己的消息，头像在右侧 -->
					<template v-else>
						<view class="self-message-container">
							<view class="message-bubble bubble-self" :class="{ 'video-message': message.type === 'video' }">
								<!-- 文本消息 -->
								<text v-if="message.type === 'text'" class="text-content">{{ message.content }}</text>
								
								<!-- 图片消息 -->
								<image
									v-else-if="message.type === 'image'"
									class="image-content"
									:src="message.imageUrl || message.content"
									mode="aspectFit"
									@click="previewImage(message.imageUrl || message.content)"
								/>

								<!-- 视频消息 -->
								<view v-else-if="message.type === 'video'" class="video-content" @click="playVideo(message)">
									<video
										class="video-player"
										:src="message.videoUrl || message.content"
										:poster="message.videoCoverUrl"
										controls
										:show-center-play-btn="true"
										:show-play-btn="true"
									/>
								</view>

								<!-- 语音消息 -->
								<view v-else-if="message.type === 'voice'" class="voice-content" @click="playVoice(message)">
									<text class="voice-icon">🎤</text>
									<text class="voice-duration">{{ message.duration }}''</text>
								</view>
								
								<!-- 消息状态 -->
								<view class="message-status">
									<text v-if="message.status === 'sending'" class="status-sending">发送中</text>
									<text v-else-if="message.status === 'sent'" class="status-sent">已发送</text>
									<text v-else-if="message.status === 'failed'" class="status-failed" @click="resendMessage(message)">重发</text>
								</view>
							</view>
							<image
								class="message-avatar"
								:src="message.sender.avatar"
								mode="aspectFill"
								@error="onAvatarError"
							/>
						</view>
					</template>
				</view>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-container">
			<!-- 工具栏 -->
			<view v-if="showToolbar" class="toolbar">
				<view class="toolbar-item" @click="selectImage">
					<text class="toolbar-icon">I</text>
					<text class="toolbar-text">图片</text>
				</view>
				<view class="toolbar-item" @click="selectVideo">
					<text class="toolbar-icon">V</text>
					<text class="toolbar-text">视频</text>
				</view>
<!--				<view class="toolbar-item" @click="shareLocation">-->
<!--					<text class="toolbar-icon">L</text>-->
<!--					<text class="toolbar-text">位置</text>-->
<!--				</view>-->
			</view>
			
			<!-- 输入框区域 -->
			<view class="input-bar">
				<view class="input-left">
					<text class="voice-btn" @click="toggleInputMode">🎙</text>
				</view>
				
				<view class="input-center">
					<textarea
						v-if="inputMode === 'text'"
						class="text-input"
						v-model="inputText"
						placeholder="输入消息..."
						:auto-height="true"
						@focus="onInputFocus"
					/>
					<!-- 语音输入界面 -->
					<view v-else class="voice-container">
						<!-- 待录音状态 -->
						<view v-if="voiceState === 'idle'" class="voice-idle" @click="startVoiceRecording">
							<text class="voice-icon">🎤</text>
							<text class="voice-text">点击说话</text>
						</view>

						<!-- 录音中状态 -->
						<view v-else-if="voiceState === 'recording'" class="voice-recording">
							<view class="recording-content">
								<text class="recording-tip">我在听，请说...</text>
								<view class="recording-progress">
									<view class="progress-bar" :style="{ width: recordingProgress + '%' }"></view>
								</view>
								<text class="recording-time">{{ formatTime(recordingTime) }}</text>
							</view>
							<view class="recording-actions">
								<view class="action-btn cancel-btn" @click="cancelVoiceRecording">
									<text class="action-icon">✕</text>
								</view>
								<view class="action-btn confirm-btn" @click="confirmVoiceRecording">
									<text class="action-icon">✓</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<view class="input-right">
					<text class="more-btn" @click="toggleToolbar">+</text>
					<button
						v-if="inputText.trim()"
						class="send-btn"
						@click="sendTextMessage"
					>
						<text class="send-icon">⏎</text>
					</button>
				</view>
			</view>
		</view>
		
		<!-- 聊天菜单弹窗 -->
		<view v-if="showMenuModal" class="menu-modal" @click="showMenuModal = false">
			<view class="menu-content" @click.stop>
				<view class="menu-option" @click="viewChatInfo">
					<text class="option-text">聊天信息</text>
				</view>
				<view class="menu-option" @click="clearChatHistory">
					<text class="option-text">清空聊天记录</text>
				</view>
			</view>
		</view>
		
		<ob-loading :visible="isLoading" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, inject, onMounted, onUnmounted, nextTick } from 'vue'
import { getPlatform, generateAvatarUrl } from '../../utils/common.js'
import messageApi from '../../api/message.js'
import { userApi } from '../../api/user.js'
import chatWebSocket from '../../utils/websocket.js'
import { getCurrentUserId } from '../../utils/userAuth.js'

const store = inject('$store')

// 响应式数据
const messages = ref([])
const chatInfo = ref({})
const inputText = ref('')
const inputMode = ref('text')
const showToolbar = ref(false)
const isLoading = ref(false)
const showMenuModal = ref(false)
const scrollIntoView = ref('')

// 语音录制相关状态
const voiceState = ref('idle') // 'idle' | 'recording'
const recordingTime = ref(0)
const recordingProgress = ref(0)
const mediaRecorder = ref(null)
const recordingTimer = ref(null)
const recordedChunks = ref([])

const platform = getPlatform()
const statusBarHeight = platform.statusBarHeight || 0

let conversationId = ''
let targetUsername = '' // 目标用户名
let targetUserId = null // 目标用户ID
let targetNickname = '' // 目标用户昵称
let currentUsername = '' // 当前用户名
let chatType = 'private' // 聊天类型：private(私聊), group(群聊)
let groupId = null // 群组ID（群聊时使用）



onMounted(() => {
	initChatData()
	loadChatMessages()
	initWebSocket()
})

onUnmounted(() => {
	// 移除消息处理器
	chatWebSocket.removeMessageHandler(handleWebSocketMessage)
	// 移除在线状态处理器
	chatWebSocket.removeOnlineStatusHandler(handleOnlineStatusChange)

	// 清理录音资源
	if (recordingTimer.value) {
		clearInterval(recordingTimer.value)
	}

	if (mediaRecorder.value && mediaRecorder.value.state !== 'inactive') {
		mediaRecorder.value.stop()
		mediaRecorder.value.stream.getTracks().forEach(track => {
			track.stop()
		})
	}
})

const initChatData = () => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options

	conversationId = options.conversationId || ''
	targetUsername = options.name || options.username || '未知用户'
	targetUserId = options.toUserId ? parseInt(options.toUserId) : null // 目标用户ID
	targetNickname = options.nickname || options.name || options.username || targetUsername || '未知用户' // 目标用户昵称
	chatType = options.type || 'private' // 从URL参数获取聊天类型
	groupId = options.groupId ? parseInt(options.groupId) : null // 群组ID
	const isCustomerService = options.isCustomerService === 'true' // 是否为客服聊天

	console.log('聊天页面参数解析:', {
		conversationId,
		targetUsername,
		targetUserId,
		targetNickname,
		nickname: options.nickname,
		name: options.name,
		username: options.username,
		isCustomerService
	})

	// 获取当前用户信息
	const userInfo = uni.getStorageSync('userInfo')
	currentUsername = userInfo?.username || userInfo?.nickname || 'user'

	// 默认头像URL
	const defaultAvatarUrl = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'

	// 初始化聊天信息，优先使用传入的头像，否则生成头像
	const initialAvatar = options.avatar || generateAvatarUrl(targetUsername)

	// 检查用户是否在线
	const isOnline = chatWebSocket.isUserOnline(targetUsername)

	chatInfo.value = {
		id: conversationId,
		name: targetUsername,
		nickname: targetNickname,
		avatar: initialAvatar,
		isOnline: isOnline,
		type: chatType,
		groupId: groupId,
		isCustomerService: isCustomerService
	}

	// 设置页面标题，如果是客服聊天则添加标识
	const pageTitle = isCustomerService ? `${targetNickname} (人工客服)` : targetNickname
	uni.setNavigationBarTitle({
		title: pageTitle
	})

	console.log('设置聊天页面标题:', targetNickname)

	// 如果没有传入头像，异步获取真实头像
	if (!options.avatar && targetUsername) {
		// 使用异步函数获取头像，不阻塞初始化
		setTimeout(() => {
			userApi.getUserInfoByUsername(targetUsername).then(userInfoResponse => {
				console.log('获取对方头像API响应:', userInfoResponse)

				if (userInfoResponse && userInfoResponse.data && userInfoResponse.data.avatar) {
					chatInfo.value.avatar = userInfoResponse.data.avatar
					console.log('成功获取对方头像:', userInfoResponse.data.avatar)
				} else {
					console.log('对方没有设置头像或响应格式异常')
				}
			}).catch(error => {
				console.error('获取对方头像失败:', error)
			})
		}, 100)
	}

	console.log('聊天初始化:', { chatType, groupId, targetUsername, targetUserId, targetNickname, conversationId })
}

const initWebSocket = () => {
	console.log('初始化WebSocket连接...')

	// 先移除旧的处理器（防止重复注册）
	chatWebSocket.removeMessageHandler(handleWebSocketMessage)
	chatWebSocket.removeOnlineStatusHandler(handleOnlineStatusChange)

	// 添加消息处理器
	chatWebSocket.addMessageHandler(handleWebSocketMessage)
	console.log('已注册消息处理器')

	// 添加在线状态变化处理器
	chatWebSocket.addOnlineStatusHandler(handleOnlineStatusChange)
	console.log('已注册在线状态处理器')

	// 强制重新连接WebSocket
	if (chatWebSocket.isConnected()) {
		console.log('WebSocket已连接，重新连接以确保稳定性')
		chatWebSocket.disconnect()
		setTimeout(() => {
			chatWebSocket.connect()
		}, 500)
	} else {
		console.log('WebSocket未连接，开始连接')
		chatWebSocket.connect()
	}

	// 添加连接状态监听
	const checkConnectionStatus = () => {
		const status = chatWebSocket.getConnectionStatus()
		console.log('WebSocket连接状态:', status)

		if (status === 'disconnected' || status === 'error') {
			console.log('检测到连接断开，尝试重连...')
			chatWebSocket.connect()
		}
	}

	// 每30秒检查一次连接状态
	setInterval(checkConnectionStatus, 30000)
}

const handleOnlineStatusChange = (onlineUsers, oldOnlineUsers) => {
	// 检查目标用户的在线状态是否发生变化
	const isOnlineNow = onlineUsers.has(targetUsername)
	const wasOnlineBefore = oldOnlineUsers.has(targetUsername)

	if (isOnlineNow !== wasOnlineBefore) {
		console.log(`用户 ${targetUsername} 在线状态变化: ${wasOnlineBefore} -> ${isOnlineNow}`)
		chatInfo.value.isOnline = isOnlineNow
	}
}

const handleWebSocketMessage = async (data) => {
  console.log('收到WebSocket消息:', data)

  // 处理接收到的消息
  if (data.fromName && data.message && !data.system) {
    // 获取当前用户ID
    const currentUserId = getCurrentUserId()

    console.log('处理聊天消息:', {
      fromId: data.fromId,
      fromName: data.fromName,
      targetUserId: targetUserId,
      targetUsername: targetUsername,
      currentUserId: currentUserId,
      chatType: data.chatType,
      groupId: data.groupId,
      currentGroupId: groupId
    })

    // 判断是否为当前聊天的消息
    let isCurrentChat = false

    if (data.chatType === 'group') {
      // 群聊消息：检查群组ID是否匹配
      isCurrentChat = data.groupId === groupId
      console.log('群聊消息判断:', {
        messageGroupId: data.groupId,
        currentGroupId: groupId,
        isMatch: isCurrentChat
      })
    } else if (data.chatType === 'private') {
      // 私聊消息：检查是否是与当前聊天对象的对话
      // 需要显示两种情况的消息：
      // 1. 对方发给我的消息：data.fromId === targetUserId && data.toId === currentUserId
      // 2. 我发给对方的消息：data.fromId === currentUserId && data.toId === targetUserId
      const isFromTarget = data.fromId === targetUserId && data.toId === currentUserId
      const isToTarget = data.fromId === currentUserId && data.toId === targetUserId

      isCurrentChat = isFromTarget || isToTarget

      console.log('私聊消息判断:', {
        messageFromId: data.fromId,
        messageToId: data.toId,
        targetUserId: targetUserId,
        currentUserId: currentUserId,
        isFromTarget: isFromTarget,
        isToTarget: isToTarget,
        isMatch: isCurrentChat
      })
    }

    console.log('是否为当前聊天消息:', isCurrentChat, {
      messageFromId: data.fromId,
      targetUserId: targetUserId,
      currentUserId: currentUserId,
      chatType: data.chatType
    })

    if (isCurrentChat) {
      const messageType = data.messageType || 'text'

      // 获取发送者头像
      let senderAvatar = null

      // 如果是自己发送的消息，优先使用当前用户的头像
      if (data.fromId === currentUserId) {
        // 获取当前用户头像
        try {
          const userInfo = uni.getStorageSync('userInfo')
          if (userInfo && userInfo.avatar &&
              userInfo.avatar.trim() !== '' &&
              userInfo.avatar !== 'identity_verified' &&
              userInfo.avatar !== 'null') {
            senderAvatar = userInfo.avatar
            console.log('✅ 使用当前用户头像:', senderAvatar)
          }
        } catch (error) {
          console.warn('获取当前用户头像失败:', error)
        }
      } else {
        // 对方发送的消息，优先使用聊天信息中的头像
        senderAvatar = chatInfo.value.avatar
      }

      // 如果头像无效，尝试从API获取
      if (!senderAvatar ||
          senderAvatar.includes('OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA') ||
          senderAvatar === 'identity_verified' ||
          senderAvatar === 'null' ||
          senderAvatar.trim() === '') {
        try {
          const userInfoResponse = await userApi.getUserInfoByUsername(data.fromName)
          if (userInfoResponse && userInfoResponse.data && userInfoResponse.data.avatar) {
            const apiAvatar = userInfoResponse.data.avatar
            // 检查API返回的头像有效性
            if (apiAvatar && apiAvatar.trim() !== '' &&
                apiAvatar !== 'identity_verified' && apiAvatar !== 'null') {
              senderAvatar = apiAvatar
              // 如果是对方的消息，同时更新聊天信息中的头像
              if (data.fromId !== currentUserId) {
                chatInfo.value.avatar = senderAvatar
              }
              console.log('✅ 从API获取头像成功:', senderAvatar)
            } else {
              console.log('⚠️ API返回的头像无效:', apiAvatar)
              senderAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
            }
          } else {
            console.log('⚠️ API未返回有效头像数据')
            senderAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
          }
        } catch (error) {
          console.warn('获取发送者头像失败，使用默认头像:', error)
          senderAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
        }
      }

      // 正确判断是否为自己发送的消息
      const isSelfMessage = data.fromId === currentUserId

      const newMessage = {
        id: 'msg_' + Date.now(),
        content: data.message,
        type: messageType,
        isSelf: isSelfMessage,
        status: isSelfMessage ? 'sent' : 'received',
        timestamp: data.timestamp || Date.now(),
        sender: {
          id: data.fromName,
          name: data.fromName,
          avatar: senderAvatar
        }
      }

      // 如果是图片消息，添加图片相关信息
      if (messageType === 'image') {
        newMessage.imageUrl = data.imageUrl || data.message
        newMessage.fileSize = data.fileSize
        newMessage.originalFilename = data.originalFilename
        console.log('处理图片消息:', {
          imageUrl: newMessage.imageUrl,
          fileSize: newMessage.fileSize,
          originalFilename: newMessage.originalFilename
        })
      }
      // 如果是视频消息，添加视频相关信息
      else if (messageType === 'video') {
        newMessage.videoUrl = data.videoUrl || data.message
        newMessage.videoDuration = data.videoDuration
        newMessage.videoWidth = data.videoWidth
        newMessage.videoHeight = data.videoHeight
        newMessage.videoCoverUrl = data.videoCoverUrl
        newMessage.fileSize = data.fileSize
        newMessage.originalFilename = data.originalFilename
        console.log('处理视频消息:', {
          videoUrl: newMessage.videoUrl,
          videoDuration: newMessage.videoDuration,
          fileSize: newMessage.fileSize,
          originalFilename: newMessage.originalFilename
        })
      }

      // 检查是否已存在相同的消息（防止重复）
      // 对于自己发送的消息，需要更严格的去重逻辑
      const existingMessage = messages.value.find(msg => {
        if (isSelfMessage) {
          // 自己发送的消息：检查内容、类型和时间戳
          return msg.content === newMessage.content &&
                 msg.type === newMessage.type &&
                 msg.isSelf === true &&
                 Math.abs(msg.timestamp - newMessage.timestamp) < 5000 // 5秒内认为是重复
        } else {
          // 对方发送的消息：检查内容、发送者和时间戳
          return msg.content === newMessage.content &&
                 msg.sender.name === newMessage.sender.name &&
                 msg.isSelf === false &&
                 Math.abs(msg.timestamp - newMessage.timestamp) < 1000 // 1秒内认为是重复
        }
      })

      if (!existingMessage) {
        console.log('添加新消息到列表:', newMessage)
        messages.value.push(newMessage)

        // 强制触发响应式更新
        nextTick(() => {
          console.log('消息列表更新，当前消息数量:', messages.value.length)
          scrollToBottom()
        })

        // 显示新消息通知
        const chatTypeName = data.chatType === 'group' ? '群聊' : '私聊'
        const messageTypeName = messageType === 'image' ? '图片' :
                               messageType === 'video' ? '视频' :
                               messageType === 'voice' ? '语音' : '文字'
        // uni.showToast({
        //   // title: `收到 ${data.fromName} 的${chatTypeName}${messageTypeName}消息`,
        //   title: `收到消息`,
        //   icon: 'none',
        //   duration: 2000
        // })
      } else {
        console.log('消息已存在，跳过添加:', newMessage.content)
      }
    } else {
      console.log('消息不属于当前聊天，忽略')
    }
  } else {
    console.log('消息格式不正确或为系统消息，忽略:', data)
  }
}

const loadChatMessages = async () => {
	try {
		isLoading.value = true
		console.log('🚀 开始加载聊天消息...')
		console.log('📋 聊天类型:', chatType)
		console.log('📋 会话ID:', conversationId)

		let response
		if (chatType === 'group' && groupId) {
			// 加载群聊消息
			const params = {
				groupId: groupId,
				page: 0,
				size: 30
			}
			response = await messageApi.getGroupChatMessages(params)
		} else {
			// 加载私聊消息
			// 获取当前用户ID
			const currentUserId = getCurrentUserId()
			console.log('👤 当前用户ID:', currentUserId)
			console.log('🎯 目标用户名:', targetUsername)
			console.log('🎯 目标用户ID:', targetUserId)

			// 如果没有目标用户ID，则通过用户名查询
			let finalTargetUserId = targetUserId
			if (!finalTargetUserId && targetUsername) {
				try {
					console.log('🔍 通过用户名查询用户ID:', targetUsername)
					const userInfoResponse = await userApi.getUserInfoByUsername(targetUsername)
					console.log('🔍 用户查询响应:', userInfoResponse)
					if (userInfoResponse && userInfoResponse.data && userInfoResponse.data.id) {
						finalTargetUserId = userInfoResponse.data.id
						console.log('✅ 获取到目标用户ID:', finalTargetUserId)
					} else {
						console.warn('⚠️ 无法获取目标用户ID，响应数据:', userInfoResponse)
					}
				} catch (error) {
					console.error('❌ 获取目标用户ID失败:', error)
				}
			}

			const params = {
				user1Id: currentUserId,
				user2Id: finalTargetUserId,
				page: 0,
				size: 30
			}

			console.log('🔍 加载聊天消息参数:', params)
			response = await messageApi.getChatMessages(params)
			console.log('🔍 API响应状态:', response ? '有响应' : '无响应')
		}

		console.log('📋 API响应数据:', response)

		// 处理不同的API响应格式
		let messagesData = null
		if (response) {
			if (response.messages) {
				messagesData = response.messages
			} else if (response.data && response.data.messages) {
				messagesData = response.data.messages
			} else if (response.data && Array.isArray(response.data)) {
				messagesData = response.data
			} else if (Array.isArray(response)) {
				messagesData = response
			}
		}

		if (messagesData && messagesData.length > 0) {
			console.log('📋 历史消息数据:', messagesData)

			// 获取当前用户ID用于判断消息归属
			const currentUserId = getCurrentUserId()

			// 转换消息格式
			messages.value = messagesData.map(msg => {
				// 直接使用数据库中保存的头像信息
				let senderAvatar = null

				// 判断是否为自己发送的消息
				let isSelfMessage = false
				if (msg.fromId) {
					isSelfMessage = msg.fromId === currentUserId
				} else {
					// 兼容旧数据，使用用户名判断
					isSelfMessage = msg.fromName === currentUsername
				}

				// 根据消息发送者选择对应的头像
				if (isSelfMessage) {
					// 自己发送的消息，使用toAvatar（对方视角下的自己头像）或fromAvatar
					senderAvatar = msg.fromAvatar
				} else {
					// 对方发送的消息，使用fromAvatar
					senderAvatar = msg.fromAvatar
				}

				// 检查头像有效性，无效则使用默认头像
				if (!senderAvatar ||
					senderAvatar === 'null' ||
					senderAvatar.trim() === '' ||
					senderAvatar === 'identity_verified') {
					senderAvatar = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
					console.log(`📷 用户 ${msg.fromName} 使用默认头像（数据库头像无效: ${msg.fromAvatar}）`)
				} else {
					console.log(`✅ 用户 ${msg.fromName} 使用数据库头像:`, senderAvatar)
				}

				return {
					id: msg.id,
					content: msg.message,
					type: msg.messageType || 'text', // 使用消息类型
					isSelf: isSelfMessage,
					timestamp: new Date(msg.timestamp).getTime(),
					sender: {
						id: msg.fromName,
						name: msg.fromName,
						avatar: senderAvatar
					},
					// 保留原始头像信息用于调试
					_debug: {
						fromAvatar: msg.fromAvatar,
						toAvatar: msg.toAvatar,
						fromName: msg.fromName,
						toName: msg.toName,
						isSelf: isSelfMessage
					}
				}
			})
		} else {
			console.log('📋 没有找到聊天消息数据')
			messages.value = []
		}

		nextTick(() => scrollToBottom())

		// 标记消息为已读
		await markMessagesAsRead()
	} catch (error) {
		console.error('加载消息失败:', error)
	} finally {
		isLoading.value = false
	}
}

/**
 * 标记消息为已读
 */
const markMessagesAsRead = async () => {
	try {
		// 获取当前用户信息
		const userInfo = uni.getStorageSync('userInfo') || {}
		const currentUserId = userInfo?.id || userInfo?.userId

		console.log('🔖 准备标记消息已读:', {
			currentUserId,
			targetUserId,
			targetUsername,
			chatType
		})

		// 只处理私聊消息的已读标记
		if (chatType !== 'private') {
			console.log('⚠️ 非私聊消息，跳过标记已读')
			return
		}

		if (!currentUserId) {
			console.warn('⚠️ 无法标记已读：缺少当前用户ID')
			return
		}

		// 获取最终的目标用户ID
		let finalTargetUserId = targetUserId
		if (!finalTargetUserId && targetUsername) {
			try {
				console.log('🔍 通过用户名查询目标用户ID:', targetUsername)
				const userInfoResponse = await userApi.getUserInfoByUsername(targetUsername)
				if (userInfoResponse && userInfoResponse.data && userInfoResponse.data.id) {
					finalTargetUserId = userInfoResponse.data.id
					console.log('✅ 获取到目标用户ID:', finalTargetUserId)
				}
			} catch (error) {
				console.error('❌ 获取目标用户ID失败:', error)
			}
		}

		// 优先尝试基于ID的方式，失败则降级到用户名方式
		let markReadSuccess = false

		if (finalTargetUserId && currentUserId) {
			try {
				// 确保参数是有效的数字
				const fromUserIdNum = parseInt(finalTargetUserId)
				const toUserIdNum = parseInt(currentUserId)

				if (!isNaN(fromUserIdNum) && !isNaN(toUserIdNum)) {
					console.log('🔖 尝试使用ID方式标记已读:', fromUserIdNum, '->', toUserIdNum)
					await messageApi.markMessagesAsReadByIds(fromUserIdNum, toUserIdNum)
					console.log('✅ ID方式标记已读成功')
					markReadSuccess = true
				} else {
					console.warn('⚠️ 用户ID不是有效数字，降级到用户名方式')
				}
			} catch (error) {
				console.warn('⚠️ ID方式标记已读失败，降级到用户名方式:', error.message)
			}
		}

		// 如果ID方式失败，使用用户名方式
		if (!markReadSuccess && targetUsername) {
			console.log('🔖 使用用户名方式标记已读')
			const currentUsername = userInfo?.username || userInfo?.nickname || 'user'
			console.log('🔖 标记已读参数:', { fromUser: targetUsername, toUser: currentUsername })
			await messageApi.markMessagesAsRead(targetUsername, currentUsername)
			console.log('✅ 用户名方式标记已读成功')
			markReadSuccess = true
		}

		if (!markReadSuccess) {
			console.warn('⚠️ 无法标记已读：缺少必要的用户信息')
		}

	} catch (error) {
		console.error('❌ 标记消息已读失败:', error)
	}
}

const loadMoreMessages = async () => {
	// 加载更多消息逻辑
}

const formatMessageTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()

  // 如果是今天的消息，只显示时间
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  // 如果是今年的消息，显示月日和时间
  else if (date.getFullYear() === now.getFullYear()) {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric'
    }) + ' ' + date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
  // 如果是其他年份的消息，显示年月日和时间
  else {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    }) + ' ' + date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

const showTimeLabel = (message, index) => {
	if (index === 0) return true
	const prevMessage = messages.value[index - 1]
	return message.timestamp - prevMessage.timestamp > 5 * 60 * 1000
}

const getBubbleClass = (message) => {
	return message.isSelf ? 'bubble-self' : 'bubble-other'
}

const onInputFocus = () => {
	showToolbar.value = false
	setTimeout(() => scrollToBottom(), 300)
}

const toggleInputMode = () => {
	inputMode.value = inputMode.value === 'text' ? 'voice' : 'text'
}

const toggleToolbar = () => {
	showToolbar.value = !showToolbar.value
}

// 语音录制相关方法
const startVoiceRecording = async () => {
	try {
		// 请求麦克风权限
		const stream = await navigator.mediaDevices.getUserMedia({ audio: true })

		// 创建MediaRecorder实例
		mediaRecorder.value = new MediaRecorder(stream)
		recordedChunks.value = []

		// 设置录音数据处理
		mediaRecorder.value.ondataavailable = (event) => {
			if (event.data.size > 0) {
				recordedChunks.value.push(event.data)
			}
		}

		// 开始录音
		mediaRecorder.value.start()
		voiceState.value = 'recording'
		recordingTime.value = 0
		recordingProgress.value = 0

		// 开始计时
		recordingTimer.value = setInterval(() => {
			recordingTime.value += 1
			recordingProgress.value = Math.min((recordingTime.value / 60) * 100, 100) // 最大60秒

			// 超过60秒自动停止
			if (recordingTime.value >= 60) {
				confirmVoiceRecording()
			}
		}, 1000)

	} catch (error) {
		console.error('录音启动失败:', error)
		uni.showToast({
			title: '无法访问麦克风',
			icon: 'none'
		})
	}
}

const cancelVoiceRecording = () => {
	stopRecording()
	voiceState.value = 'idle'
	uni.showToast({
		title: '录音已取消',
		icon: 'none'
	})
}

const confirmVoiceRecording = () => {
	if (recordingTime.value < 1) {
		uni.showToast({
			title: '录音时间太短',
			icon: 'none'
		})
		return
	}

	stopRecording()
	processVoiceMessage()
}

const stopRecording = () => {
	if (recordingTimer.value) {
		clearInterval(recordingTimer.value)
		recordingTimer.value = null
	}

	if (mediaRecorder.value && mediaRecorder.value.state !== 'inactive') {
		mediaRecorder.value.stop()

		// 停止所有音频轨道
		mediaRecorder.value.stream.getTracks().forEach(track => {
			track.stop()
		})
	}
}

const processVoiceMessage = () => {
	if (recordedChunks.value.length === 0) {
		voiceState.value = 'idle'
		return
	}

	// 创建音频文件
	const audioBlob = new Blob(recordedChunks.value, { type: 'audio/webm' })

	// 这里可以上传音频文件或转换格式
	sendVoiceMessage(audioBlob, recordingTime.value)

	voiceState.value = 'idle'
}

const sendVoiceMessage = async (audioBlob, duration) => {
	try {
		// 创建FormData上传音频
		const formData = new FormData()
		formData.append('audio', audioBlob, 'voice.webm')
		formData.append('duration', duration)

		// 这里需要根据您的后端API调整
		// const response = await messageApi.uploadVoice(formData)

		// 临时处理：创建本地URL用于预览
		const audioUrl = URL.createObjectURL(audioBlob)

		// 发送语音消息
		const voiceMessage = {
			id: Date.now().toString(),
			type: 'voice',
			content: audioUrl,
			duration: duration,
			timestamp: Date.now(),
			isSelf: true,
			sender: {
				id: getCurrentUserId(),
				name: '我',
				avatar: userAvatar.value
			},
			status: 'sent'
		}

		messages.value.push(voiceMessage)
		scrollToBottom()

		uni.showToast({
			title: '语音发送成功',
			icon: 'success'
		})

	} catch (error) {
		console.error('语音发送失败:', error)
		uni.showToast({
			title: '语音发送失败',
			icon: 'none'
		})
	}
}

const formatTime = (seconds) => {
	const mins = Math.floor(seconds / 60)
	const secs = seconds % 60
	return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}



const sendTextMessage = async () => {
	if (!inputText.value.trim()) return
	
	const messageContent = inputText.value.trim()

	// 获取自己的头像
	const selfAvatar = await getCurrentUserAvatar('text')

	// 添加消息到界面
	const tempMessage = {
		id: 'msg_' + Date.now(),
		content: messageContent,
		type: 'text',
		isSelf: true,
		status: 'sending',
		timestamp: Date.now(),
		sender: {
			id: currentUsername,
			name: currentUsername,
			avatar: selfAvatar
		}
	}

	messages.value.push(tempMessage)
	inputText.value = ''
	nextTick(() => scrollToBottom())
	
	// 检查WebSocket连接状态
	if (!chatWebSocket.isConnected()) {
		console.log('WebSocket未连接，尝试重连...')
		chatWebSocket.reconnect()
		
		// 等待连接成功
		await new Promise((resolve) => {
			const checkConnection = () => {
				if (chatWebSocket.isConnected()) {
					resolve()
				} else if (chatWebSocket.getConnectionStatus() === 'failed') {
					resolve() // 连接失败也要继续执行
				} else {
					setTimeout(checkConnection, 100)
				}
			}
			checkConnection()
		})
	}
	
	// 通过WebSocket发送消息
	try {
		let success = false
		if (chatType === 'group' && groupId) {
			// 发送群聊消息
			success = chatWebSocket.sendGroupMessage(groupId, messageContent)
		} else {
			// 发送私聊消息（现在是异步的），传递目标用户ID
			success = await chatWebSocket.sendMessage(targetUsername, messageContent, 'text', targetUserId)
		}

		const messageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
		if (messageIndex > -1) {
			if (success) {
				messages.value[messageIndex].status = 'sent'
			} else {
				messages.value[messageIndex].status = 'failed'

				uni.showToast({
					title: '发送失败，点击重发',
					icon: 'none'
				})
			}
		}
	} catch (error) {
		console.error('发送消息错误:', error)

		// 更新消息状态为失败
		const messageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
		if (messageIndex > -1) {
			messages.value[messageIndex].status = 'failed'
		}
	}
}

// 上传并发送视频
const uploadAndSendVideo = async (tempFilePath, duration, width, height) => {
	console.log('开始上传视频:', {
		tempFilePath,
		duration,
		width,
		height
	})

	try {
		// 获取自己的头像
		const selfAvatar = await getCurrentUserAvatar('video')
		console.log('获取到自己的头像:', selfAvatar)

		// 创建临时视频消息
		const tempMessage = {
			id: 'video_' + Date.now(),
			content: tempFilePath, // 临时使用本地路径
			type: 'video',
			isSelf: true,
			status: 'uploading',
			timestamp: Date.now(),
			videoDuration: duration,
			videoWidth: width,
			videoHeight: height,
			sender: {
				id: currentUsername,
				name: currentUsername,
				avatar: selfAvatar
			}
		}

		console.log('创建临时视频消息:', tempMessage)
		messages.value.push(tempMessage)
		nextTick(() => scrollToBottom())

		// 获取文件信息
		let fileInfo = null
		try {
			fileInfo = await uni.getFileInfo({
				filePath: tempFilePath
			})
			console.log('视频文件信息:', fileInfo)
		} catch (e) {
			console.warn('获取文件信息失败:', e)
		}

		// 上传视频到服务器
		console.log('开始调用视频上传API:', {
			fromUser: currentUsername,
			toUser: targetUsername,
			file: tempFilePath
		})

		const uploadResult = await messageApi.uploadChatVideo({
			fromUser: currentUsername,
			toUser: targetUsername,
			file: tempFilePath
		})

		console.log('视频上传API响应:', uploadResult)

		if (uploadResult && uploadResult.success) {
			const videoUrl = uploadResult.data.videoUrl

			// 更新消息内容为服务器URL
			const messageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
			if (messageIndex > -1) {
				messages.value[messageIndex].content = videoUrl
				messages.value[messageIndex].status = 'sending'
			}

			// 检查WebSocket连接状态
			if (!chatWebSocket.isConnected()) {
				console.log('WebSocket未连接，尝试重连...')
				chatWebSocket.reconnect()

				// 等待连接成功
				await new Promise((resolve) => {
					const checkConnection = () => {
						if (chatWebSocket.isConnected()) {
							resolve()
						} else if (chatWebSocket.getConnectionStatus() === 'failed') {
							resolve()
						} else {
							setTimeout(checkConnection, 100)
						}
					}
					checkConnection()
				})
			}

			// 通过WebSocket发送视频消息
			let success = false
			const videoMessageData = {
				message: videoUrl,
				messageType: 'video',
				fileSize: fileInfo ? fileInfo.size : uploadResult.data.fileSize,
				originalFilename: uploadResult.data.originalFilename,
				videoDuration: duration,
				videoWidth: width,
				videoHeight: height
			}

			if (chatType === 'group' && groupId) {
				// 发送群聊视频消息
				success = chatWebSocket.sendGroupVideoMessage(groupId, videoMessageData)
			} else {
				// 发送私聊视频消息
				success = chatWebSocket.sendVideoMessage(targetUsername, videoMessageData, targetUserId)
			}

			// 更新消息状态
			const finalMessageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
			if (finalMessageIndex > -1) {
				if (success) {
					messages.value[finalMessageIndex].status = 'sent'
				} else {
					messages.value[finalMessageIndex].status = 'failed'
					uni.showToast({
						title: '视频发送失败',
						icon: 'none'
					})
				}
			}

		} else {
			// 上传失败，移除临时消息
			const messageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
			if (messageIndex > -1) {
				messages.value.splice(messageIndex, 1)
			}

			console.error('视频上传失败:', uploadResult)
			uni.showToast({
				title: uploadResult.message || '视频上传失败',
				icon: 'none'
			})
		}

	} catch (error) {
		console.error('视频上传失败:', error)
		console.error('错误详情:', {
			message: error.message,
			stack: error.stack,
			name: error.name
		})

		// 查找并移除失败的消息
		const failedMessageIndex = messages.value.findIndex(msg =>
			msg.type === 'video' && msg.status === 'uploading' && msg.content === tempFilePath
		)
		if (failedMessageIndex > -1) {
			messages.value.splice(failedMessageIndex, 1)
		}

		// 显示详细错误信息
		const errorMessage = error.message || '视频上传失败'
		uni.showToast({
			title: errorMessage.length > 20 ? '视频上传失败' : errorMessage,
			icon: 'none',
			duration: 3000
		})

		// 在控制台显示完整错误信息
		console.error('完整错误信息:', errorMessage)
	}
}

// 上传并发送图片
const uploadAndSendImage = async (tempFilePath) => {
	console.log('开始上传图片:', tempFilePath)
	try {
		// 获取自己的头像
		const selfAvatar = await getCurrentUserAvatar('image')
		console.log('获取到自己的头像:', selfAvatar)

		// 创建临时图片消息
		const tempMessage = {
			id: 'img_' + Date.now(),
			content: tempFilePath, // 临时使用本地路径
			type: 'image',
			isSelf: true,
			status: 'uploading',
			timestamp: Date.now(),
			sender: {
				id: currentUsername,
				name: currentUsername,
				avatar: selfAvatar
			}
		}

		console.log('创建临时图片消息:', tempMessage)
		messages.value.push(tempMessage)
		nextTick(() => scrollToBottom())

		// 获取文件信息
		let fileInfo = null
		try {
			fileInfo = await uni.getFileInfo({
				filePath: tempFilePath
			})
			console.log('文件信息:', fileInfo)
		} catch (e) {
			console.warn('获取文件信息失败:', e)
		}

		// 上传图片到服务器
		console.log('开始调用上传API:', {
			fromUser: currentUsername,
			toUser: targetUsername,
			file: tempFilePath
		})

		const uploadResult = await messageApi.uploadChatImage({
			fromUser: currentUsername,
			toUser: targetUsername,
			file: tempFilePath
		})

		console.log('图片上传API响应:', uploadResult)

		if (uploadResult && uploadResult.success) {
			const imageUrl = uploadResult.data.imageUrl
			console.log('图片上传成功，URL:', imageUrl)

			// 更新消息内容为服务器URL
			const messageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
			if (messageIndex > -1) {
				messages.value[messageIndex].content = imageUrl
				messages.value[messageIndex].status = 'sending'
				console.log('更新消息状态为sending')
			}

			// 检查WebSocket连接状态
			if (!chatWebSocket.isConnected()) {
				console.log('WebSocket未连接，尝试重连...')
				chatWebSocket.reconnect()

				// 等待连接成功
				await new Promise((resolve) => {
					const checkConnection = () => {
						if (chatWebSocket.isConnected()) {
							console.log('WebSocket重连成功')
							resolve()
						} else if (chatWebSocket.getConnectionStatus() === 'failed') {
							console.log('WebSocket重连失败')
							resolve()
						} else {
							setTimeout(checkConnection, 100)
						}
					}
					checkConnection()
				})
			}

			// 通过WebSocket发送图片消息
			let success = false
			const imageMessageData = {
				message: imageUrl,
				messageType: 'image',
				fileSize: fileInfo ? fileInfo.size : uploadResult.data.fileSize,
				originalFilename: uploadResult.data.originalFilename
			}

			console.log('准备发送图片消息:', imageMessageData)

			if (chatType === 'group' && groupId) {
				// 发送群聊图片消息
				console.log('发送群聊图片消息')
				success = chatWebSocket.sendGroupImageMessage(groupId, imageMessageData)
			} else {
				// 发送私聊图片消息
				console.log('发送私聊图片消息')
				success = chatWebSocket.sendImageMessage(targetUsername, imageMessageData, targetUserId)
			}

			console.log('图片消息发送结果:', success)

			// 更新消息状态
			const finalMessageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
			if (finalMessageIndex > -1) {
				if (success) {
					messages.value[finalMessageIndex].status = 'sent'
					console.log('图片消息发送成功')
				} else {
					messages.value[finalMessageIndex].status = 'failed'
					console.log('图片消息发送失败')
					uni.showToast({
						title: '图片发送失败',
						icon: 'none'
					})
				}
			}

		} else {
			// 上传失败
			console.error('图片上传失败:', uploadResult)
			const messageIndex = messages.value.findIndex(msg => msg.id === tempMessage.id)
			if (messageIndex > -1) {
				messages.value[messageIndex].status = 'failed'
			}

			const errorMsg = uploadResult?.message || '图片上传失败'
			console.error('上传失败原因:', errorMsg)
			uni.showToast({
				title: errorMsg,
				icon: 'none',
				duration: 3000
			})
		}

	} catch (error) {
		console.error('上传图片失败:', error)
		console.error('错误详情:', {
			message: error.message,
			stack: error.stack,
			name: error.name
		})

		// 查找并更新消息状态
		const messageIndex = messages.value.findIndex(msg =>
			msg.content === tempFilePath && msg.status === 'uploading'
		)
		if (messageIndex > -1) {
			messages.value[messageIndex].status = 'failed'
			console.log('更新消息状态为failed')
		}

		const errorMsg = error.message || '图片上传失败'
		console.error('最终错误信息:', errorMsg)
		uni.showToast({
			title: errorMsg.length > 20 ? '图片上传失败' : errorMsg,
			icon: 'none',
			duration: 3000
		})
	}
}

const selectImage = () => {
	console.log('用户点击选择图片')
	uni.chooseImage({
		count: 9,
		sizeType: ['original', 'compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			console.log('选择图片成功:', res.tempFilePaths)
			console.log('图片数量:', res.tempFilePaths.length)

			// 处理每张选中的图片
			for (let i = 0; i < res.tempFilePaths.length; i++) {
				const tempFilePath = res.tempFilePaths[i]
				console.log(`开始处理第${i + 1}张图片:`, tempFilePath)
				try {
					await uploadAndSendImage(tempFilePath)
					console.log(`第${i + 1}张图片处理完成`)
				} catch (error) {
					console.error(`第${i + 1}张图片处理失败:`, error)
					uni.showToast({
						title: `第${i + 1}张图片发送失败`,
						icon: 'none'
					})
				}
			}
		},
		fail: (err) => {
			console.error('选择图片失败:', err)
			uni.showToast({
				title: '选择图片失败: ' + (err.errMsg || '未知错误'),
				icon: 'none',
				duration: 3000
			})
		}
	})
	showToolbar.value = false
}

const selectVideo = () => {
	console.log('用户点击选择视频')
	uni.chooseVideo({
		maxDuration: 60, // 最大60秒
		camera: 'back',
		success: async (res) => {
			console.log('选择视频成功:', res)
			console.log('视频信息:', {
				tempFilePath: res.tempFilePath,
				duration: res.duration,
				width: res.width,
				height: res.height,
				size: res.size
			})

			try {
				await uploadAndSendVideo(res.tempFilePath, res.duration, res.width, res.height)
				console.log('视频处理完成')
			} catch (error) {
				console.error('视频处理失败:', error)
				uni.showToast({
					title: '视频发送失败: ' + (error.message || '未知错误'),
					icon: 'none',
					duration: 3000
				})
			}
		},
		fail: (err) => {
			console.error('选择视频失败:', err)
			uni.showToast({
				title: '选择视频失败: ' + (err.errMsg || '未知错误'),
				icon: 'none',
				duration: 3000
			})
		}
	})
	showToolbar.value = false
}

const shareLocation = () => {
	uni.showToast({
		title: '位置分享功能开发中',
		icon: 'none'
	})
	showToolbar.value = false
}

const previewImage = (imageUrl) => {
	uni.previewImage({
		urls: [imageUrl],
		current: imageUrl
	})
}

// 播放视频
const playVideo = (message) => {
	console.log('播放视频:', message)
	// 视频会自动播放，这里可以添加额外的逻辑
}

// 格式化视频时长
const formatVideoDuration = (duration) => {
	if (!duration) return '00:00'

	const minutes = Math.floor(duration / 60)
	const seconds = Math.floor(duration % 60)

	return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const playVoice = (message) => {
	console.log('播放语音:', message)
}

// 头像加载错误处理
const onAvatarError = (e) => {
	console.log('头像加载失败，使用默认头像')
	e.target.src = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
}

const resendMessage = async (message) => {
	message.status = 'sending'
	
	try {
		// 检查WebSocket连接
		if (!chatWebSocket.isConnected()) {
			chatWebSocket.reconnect()
			
			// 等待连接
			await new Promise((resolve) => {
				const checkConnection = () => {
					if (chatWebSocket.isConnected()) {
						resolve()
					} else if (chatWebSocket.getConnectionStatus() === 'failed') {
						resolve()
					} else {
						setTimeout(checkConnection, 100)
					}
				}
				checkConnection()
			})
		}
		
		const success = await chatWebSocket.sendMessage(targetUsername, message.content, 'text', targetUserId)
		
		if (success) {
			message.status = 'sent'
			uni.showToast({
				title: '重发成功',
				icon: 'success'
			})
		} else {
			message.status = 'failed'
			uni.showToast({
				title: '重发失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('重发消息失败:', error)
		message.status = 'failed'
	}
}

const goBack = () => {
	uni.navigateBack()
}

// 获取当前用户头像的辅助函数
const getCurrentUserAvatar = async (messageType = 'text') => {
	const userInfo = uni.getStorageSync('userInfo')
	const defaultAvatarUrl = 'https://ts1.tc.mm.bing.net/th/id/OIP-C.4qE6UmzbSk0mCOn2uWMELAAAAA?rs=1&pid=ImgDetMain&o=7&rm=3'
	let selfAvatar = defaultAvatarUrl

	console.log(`📋 ${messageType}消息 - 获取自己头像 - userInfo:`, userInfo)

	// 第一步：从localStorage的userInfo中获取头像
	if (userInfo && userInfo.avatar &&
		userInfo.avatar !== 'identity_verified' &&
		userInfo.avatar !== 'null' &&
		userInfo.avatar.trim() !== '') {
		selfAvatar = userInfo.avatar
		console.log(`✅ ${messageType}消息 - 从localStorage获取到头像:`, selfAvatar)
		return selfAvatar
	}

	console.log(`⚠️ ${messageType}消息 - localStorage中没有有效头像`)

	// 第二步：如果是文本消息且localStorage中没有头像，尝试通过API获取
	if (messageType === 'text') {
		try {
			const currentUserId = userInfo?.id || userInfo?.userId
			const currentUsername = userInfo?.username || userInfo?.nickname || 'user'

			if (currentUserId) {
				console.log('📡 调用API获取用户头像，用户ID:', currentUserId)
				const userInfoResponse = await userApi.getUserInfoByUsername(currentUsername)
				console.log('📡 API响应:', userInfoResponse)

				if (userInfoResponse && userInfoResponse.data && userInfoResponse.data.avatar &&
					userInfoResponse.data.avatar !== 'identity_verified' &&
					userInfoResponse.data.avatar !== 'null' &&
					userInfoResponse.data.avatar.trim() !== '') {
					selfAvatar = userInfoResponse.data.avatar
					console.log('✅ 通过API获取到头像:', selfAvatar)

					// 更新localStorage中的用户信息，避免下次重复请求
					const updatedUserInfo = { ...userInfo, avatar: userInfoResponse.data.avatar }
					uni.setStorageSync('userInfo', updatedUserInfo)
					console.log('💾 已更新localStorage中的用户头像')
				} else {
					console.log('⚠️ API返回的头像无效，使用默认头像')
				}
			} else {
				console.log('❌ 无法获取用户ID，使用默认头像')
			}
		} catch (error) {
			console.warn('❌ 通过API获取当前用户头像失败，使用默认头像:', error)
		}
	}

	console.log(`🎯 ${messageType}消息 - 最终使用的头像:`, selfAvatar)
	return selfAvatar
}

const viewProfile = () => {
	uni.navigateTo({
		url: `/pages/profile/user?userId=${chatInfo.value.id}`
	})
}

const showChatMenu = () => {
	showMenuModal.value = true
}

const viewChatInfo = () => {
	showMenuModal.value = false
	uni.navigateTo({
		url: `/pages/message/chat-info?conversationId=${conversationId}`
	})
}

const clearChatHistory = () => {
	showMenuModal.value = false
	uni.showModal({
		title: '清空聊天记录',
		content: '确定要清空所有聊天记录吗？',
		success: (res) => {
			if (res.confirm) {
				messages.value = []
				uni.showToast({
					title: '已清空',
					icon: 'success'
				})
			}
		}
	})
}

const scrollToBottom = () => {
	if (messages.value.length > 0) {
		const lastMessage = messages.value[messages.value.length - 1]
		scrollIntoView.value = 'message-' + lastMessage.id
	}
}
</script>

<style lang="scss" scoped>
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background: #F5F5F5;
}

.chat-header {
	background: #FFFFFF;
	border-bottom: 1px solid #E5E5E5;
	z-index: 100;
}

.header-content {
	display: flex;
	align-items: center;
	height: 50px;
	padding: 0 15px;
}

.header-left {
	width: 40px;
	.back-icon {
		font-size: 20px;
		color: #333333;
	}
}

.header-center {
	flex: 1;
	display: flex;
	align-items: center;
	gap: 10px;
}

.avatar-container {
	position: relative;
}

.header-avatar {
	width: 35px;
	height: 35px;
	border-radius: 17px;
}

.service-badge {
	position: absolute;
	bottom: -2px;
	right: -2px;
	background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
	border-radius: 8px;
	padding: 1px 4px;
	min-width: 20px;
	height: 14px;
	display: flex;
	align-items: center;
	justify-content: center;
	border: 1px solid #ffffff;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.service-text {
	font-size: 8px;
	color: #ffffff;
	font-weight: 600;
	line-height: 1;
}

.header-info {
	flex: 1;
	.header-name {
		font-size: 16px;
		font-weight: 600;
		color: #333333;
		display: block;
		margin-bottom: 2px;
	}
	.header-status {
		font-size: 12px;
		color: #999999;

		&.service-status {
			color: #ff6b6b;
			font-weight: 600;
		}
	}
}

.header-right {
	width: 40px;
	text-align: right;
	.menu-icon {
		font-size: 16px;
		color: #333333;
	}
}

.message-list {
	flex: 1;
	padding: 10px 15px;
}

.message-item {
	margin-bottom: 15px;
}

.time-divider {
	text-align: center;
	margin: 10px 0;
	.time-text {
		font-size: 12px;
		color: #999999;
		background: rgba(0, 0, 0, 0.1);
		padding: 4px 8px;
		border-radius: 10px;
	}
}

.message-content {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  width: 100%;
}

.self-message-container {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  width: 100%;
  justify-content: flex-end;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  flex-shrink: 0;
}

.message-bubble {
  max-width: 85%;
  padding: 10px 12px;
  border-radius: 18px;
  position: relative;

  // 针对视频消息的特殊样式
  &.video-message {
    max-width: 90%;
    padding: 2px;
    background: transparent;
    border: none;
  }

  &.bubble-self:not(.video-message) {
    background: #0079FE;
    .text-content {
      color: #FFFFFF;
    }
  }

  &.bubble-other:not(.video-message) {
    background: #FFFFFF;
    border: 1px solid #E5E5E5;
    .text-content {
      color: #333333;
    }
  }

  .text-content {
    font-size: 16px;
    line-height: 1.4;
    word-wrap: break-word;
  }

  .image-content {
    max-width: 200px;
    max-height: 200px;
    border-radius: 8px;
  }

  .video-content {
    position: relative;
    width: 100%;
    max-width: min(400px, 80vw);
    min-width: 250px;
    border-radius: 6px;
    overflow: hidden;
    background: transparent;
  }

  .video-player {
    width: 100%;
    min-height: 250px;
    max-height: min(400px, 60vh);
    height: auto;
    border-radius: 6px;
    object-fit: cover;
    display: block;
  }


}

// 响应式设计 - 针对不同屏幕尺寸的优化
@media screen and (max-width: 480px) {
  .message-bubble {
    &.video-message {
      max-width: 95%;
      padding: 2px;
    }

    .video-content {
      max-width: min(350px, 90vw);
      min-width: 200px;
    }

    .video-player {
      min-height: 200px;
      max-height: min(350px, 50vh);
    }
  }
}

@media screen and (min-width: 768px) {
  .message-bubble {
    &.video-message {
      max-width: 80%;
      padding: 2px;
    }

    .video-content {
      max-width: min(500px, 70vw);
      min-width: 300px;
    }

    .video-player {
      min-height: 300px;
      max-height: min(450px, 60vh);
    }
  }
}

  .voice-content {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 80px;
    .voice-icon {
      font-size: 16px;
    }
    .voice-duration {
      font-size: 14px;
    }
  }


.message-status {
  margin-top: 4px;
  text-align: right;
  font-size: 10px;
  .status-sending,
  .status-sent {
    color: rgba(255, 255, 255, 0.8);
  }
  .status-failed {
    color: #ff4757;
  }
}

.input-container {
	background: #FFFFFF;
	border-top: 1px solid #E5E5E5;
}

.toolbar {
	display: flex;
	padding: 15px;
	gap: 20px;
	border-bottom: 1px solid #F0F0F0;
}

.toolbar-item {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 8px;
	border-radius: 8px;
	
	&:active {
		background: #F8F9FA;
	}
	
	.toolbar-icon {
		font-size: 18px;
		font-weight: 600;
		color: #6C757D;
		margin-bottom: 4px;
		width: 24px;
		height: 24px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 4px;
		background: #F8F9FA;
		border: 1px solid #E9ECEF;
	}
	
	.toolbar-text {
		font-size: 12px;
		color: #666666;
	}
}

.input-bar {
	display: flex;
	align-items: flex-end;
	padding: 10px 15px;
	gap: 10px;
	min-height: 55px; /* 确保最小高度 */
}

.input-left,
.input-right {
	display: flex;
	align-items: center;
	gap: 8px;
	flex-shrink: 0; /* 防止被压缩 */
}

.voice-btn {
	width: 35px;
	height: 35px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 17px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	color: #6C757D;
	
	&:active {
		background: #E9ECEF;
	}
}

.input-center {
	flex: 1;
	min-height: 35px;
	max-height: 100px;
	min-width: 0; /* 允许缩小但不会被完全压缩 */
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 17px;
	padding: 8px 12px;
	display: flex;
	align-items: center;
}

.text-input {
	flex: 1;
	font-size: 16px;
	line-height: 1.4;
	background: transparent;
	border: none;
	min-width: 0; /* 防止内容过长时压缩右侧按钮 */
	max-width: 100%; /* 限制最大宽度 */
	color: #333333;
}

/* 语音输入容器 */
.voice-container {
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

/* 待录音状态 */
.voice-idle {
	display: flex;
	align-items: center;
	justify-content: center;
	gap: 8px;
	padding: 8px 16px;
	background: #F0F0F0;
	border-radius: 20px;
	border: 1px solid #E0E0E0;
	cursor: pointer;
	transition: all 0.2s ease;

	&:hover {
		background: #E8E8E8;
	}

	&:active {
		background: #D8D8D8;
		transform: scale(0.98);
	}
}

.voice-icon {
	font-size: 18px;
	color: #007AFF;
}

.voice-text {
	font-size: 16px;
	color: #666666;
	font-weight: 500;
}

/* 录音中状态 */
.voice-recording {
	width: 100%;
	background: #F8F9FA;
	border: 2px solid #007AFF;
	border-radius: 20px;
	padding: 16px;
	display: flex;
	flex-direction: column;
	gap: 12px;
}

.recording-content {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8px;
}

.recording-tip {
	font-size: 16px;
	color: #333333;
	font-weight: 500;
}

.recording-progress {
	width: 100%;
	height: 4px;
	background: #E0E0E0;
	border-radius: 2px;
	overflow: hidden;
	position: relative;
}

.progress-bar {
	height: 100%;
	background: linear-gradient(90deg, #007AFF 0%, #00C7FF 100%);
	border-radius: 2px;
	transition: width 0.3s ease;
}

.recording-time {
	font-size: 18px;
	color: #007AFF;
	font-weight: 600;
	font-family: 'Courier New', monospace;
}

.recording-actions {
	display: flex;
	justify-content: center;
	gap: 20px;
}

.action-btn {
	width: 44px;
	height: 44px;
	border-radius: 22px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.2s ease;

	&:active {
		transform: scale(0.95);
	}
}

.cancel-btn {
	background: #FF3B30;

	&:hover {
		background: #E6342A;
	}

	.action-icon {
		color: #FFFFFF;
		font-size: 20px;
		font-weight: bold;
	}
}

.confirm-btn {
	background: #34C759;

	&:hover {
		background: #2FB84D;
	}

	.action-icon {
		color: #FFFFFF;
		font-size: 20px;
		font-weight: bold;
	}
}



.more-btn {
	width: 35px;
	height: 35px;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 17px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 16px;
	color: #6C757D;
	flex-shrink: 0; /* 确保按钮不被压缩 */

	&:active {
		background: #E9ECEF;
	}
}

.send-btn {
	background: #F8F9FA; /* 浅灰色背景，符合极简风格 */
	border: 1px solid #E9ECEF; /* 添加边框 */
	border-radius: 17px;
	padding: 8px;
	height: 35px;
	width: 35px; /* 设置固定宽度，保持圆形 */
	flex-shrink: 0; /* 确保按钮不被压缩 */
	display: flex;
	align-items: center;
	justify-content: center;
	
	.send-icon {
		color: #6C757D; /* 中灰色图标 */
		font-size: 16px;
		font-weight: 500;
		line-height: 1;
	}
	
	&:active {
		background: #E9ECEF;
		.send-icon {
			color: #495057;
		}
	}
	
	&:hover {
		background: #E9ECEF;
	}
}

.menu-modal {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 1000;
	display: flex;
	align-items: center;
	justify-content: center;
}

.menu-content {
	background: #FFFFFF;
	border-radius: 8px;
	margin: 0 40px;
	overflow: hidden;
}

.menu-option {
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
	&:last-child {
		border-bottom: none;
	}
	&:active {
		background: #F8F9FA;
	}
	.option-text {
		font-size: 16px;
		color: #333333;
	}
}

.empty-messages {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
	text-align: center;

	.empty-text {
		font-size: 16px;
		color: #6C757D;
		margin-bottom: 8px;
	}

	.empty-desc {
		font-size: 14px;
		color: #ADB5BD;
	}
}
</style>